package com.dynamic.mybatis.bootstrap.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dynamic.mybatis.bootstrap.entity.MappedStatementEntity;
import com.dynamic.mybatis.bootstrap.service.MappedStatementService;
import com.dynamic.mybatis.core.intercept.DynamicMappedStatementHandler;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description
 * @Author xs
 * @Date 2023/5/23 13:28
 */
@Component
public class MyMappedStatementHandler implements DynamicMappedStatementHandler {
    @Autowired
    @Lazy
    private MappedStatementService mappedStatementService;


    @Override
    public void before(OPERATE operate, DynamicMappedStatement dms) {
        System.err.println("before mappedStatement handle.   " + operate + "   " + dms.getId());
    }

    @Override
    public void after(OPERATE operate, DynamicMappedStatement dms) {
        System.err.println("after mappedStatement handle.    " + operate + "   " + dms.getId());
        LambdaQueryWrapper<MappedStatementEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MappedStatementEntity::getUniqueCode, dms.getId());
        wrapper.eq(MappedStatementEntity::getIsDeleted, 0);
        List<MappedStatementEntity> list = mappedStatementService.list(wrapper);

        MappedStatementEntity entity = new MappedStatementEntity();
        if (CollectionUtils.isNotEmpty(list)) {
            entity.setId(list.get(0).getId());
        }

        entity.setNamespace(dms.getNamespace());
        entity.setCode(dms.getShortId());
        entity.setUniqueCode(dms.getId());
        entity.setName(dms.getName());
        entity.setParentUniqueCode(dms.getParentId());
        entity.setDataSourceUniqueCodes(JSON.toJSONString(dms.getDynamicDataSourceKeys()));
        entity.setCommandType(dms.getCommandType().commandType());
        entity.setSqlStatement(dms.getSqlStatement());
        entity.setReturnType(dms.getReturnType().returnType());
        entity.setInputParameter(JSON.toJSONString(dms.getInputParameter()));
        entity.setOutputParameter(JSON.toJSONString(dms.getOutputParameter()));
        entity.setTables(JSON.toJSONString(dms.getTables()));
        entity.setStatus(dms.isEnable() ? (byte) 1 : (byte) 0);
        entity.setCreateBy(dms.getCreateBy());
        entity.setUpdateBy(dms.getUpdateBy());
        mappedStatementService.save(entity);
        System.out.print(JSON.toJSONString(dms.getInputParameter(), JSONWriter.Feature.PrettyFormat));
    }
}